<script setup>
import { nextTick, ref } from "vue";
import { useRouter } from "vue-router";
import { staffList } from "@/utils/constClass.js";
import { querySysUser, changeSysUserStatus, deleteSysUser } from "@/api/System";
import TabDepartment from "@/components/TableComponents/Department.vue";
import TabRole from "@/components/TableComponents/Role.vue";
import {
  queryDepartmentListPage,
  queryRoleList,
} from "@/api/System";
const tableLoading = ref(false);
const seachTableRef = ref();
const messageBoxRef = ref();
const router = useRouter();
const instance = getCurrentInstance();
const formInline = ref([
  {
    type: "input",
    prop: "employeeNameOrUserAccount",
    placeholder: "员工姓名/登录帐号",
    label: "",
    model: "",
  },
  {
    type: "select",
    placeholder: "部门",
    label: "",
    multiple: true,
    width: "180px",
    prop: "departmentIdList",
    data: [],
    model: [],
    loading: false,
    remote: true,
  },
  {
    type: "select",
    placeholder: "角色",
    label: "",
    multiple: true,
    width: "180px",
    prop: "roleIdList",
    data: [],
    model: [],
    loading: false,
    remote: true,
  },
  {
    type: "select",
    placeholder: "状态",
    label: "",
    width: "180px",
    prop: "accountStatusList",
    multiple: true,
    data: staffList,
    model: [],
  },
]);
const btnLefts = ref([
  {
    label: "新增员工",
    plain: false,
    type: "primary",
    show: true,
    img: new URL("@/assets/icon/btn-add.png", import.meta.url),
    click: async () => {
      router.push({ name: "StaffManageAdd" });
    },
  },
]);
const tableConfig = ref([
  {
    prop: "employeeName",
    label: "员工姓名",
    width:"150"
  },
  {
    prop: "userAccount",
    label: "登录账号",
    width:"150"
  },
  {
    prop: "userRoleList",
    label: "角色",
    type: "slot",
    textOverflow: true,
    slotName: "userRoleList",
  },
  {
    prop: "accountStatus",
    label: "状态",
    type: "slot",
    width: "80",
    slotName: "accountStatus",
  },
  {
    prop: "userDepartmentList",
    label: "部门",
    type: "slot",
    textOverflow: true,
    slotName: "userDepartmentList",
  },
  {
    prop: "lastUpdateTime",
    label: "最新更新",
    width: "180",
  },
  {
    type: "action",
    label: "操作",
    width: 170,
    btns: [
      {
        label: () => "编辑",
        type: "success",
        show: (row) => {
          return row.accountType != 1 && true;
        },
        click: async (row) => {
          router.push({
            name: "StaffManageEdit",
            query: { uuid: row.id },
          });
        },
      },
      {
        label: () => "删除",
        type: "danger",
        show: (row) => {
          return row.accountType != 1 && true;
        },
        click: async (row) => {
          delMessageBoxRef.value.open();
          delItem.value = row;
        },
      },
    ],
  },
]);

const totalPage = ref(0);
const tableData = ref([]);

const handlerSearch = async (formInline) => {
  tableLoading.value = true;
  try {
    const { records, total } = await querySysUser(formInline);
    totalPage.value = Number(total);
    tableData.value = records.map((v) => ({ ...v, switchLoading: false }));
    tableLoading.value = false;
  } catch (e) {
    tableLoading.value = false;
  }
};
const switchChange = async () => {
  nextTick(() => {
    if (activeItem.value.accountStatus) {
      messageBoxRef.value.open();
    } else {
      messageConfirm();
    }
  });
};
const messageConfirm = async () => {
  activeItem.value.switchLoading = true;
  try {
    // 拉取数据
    activeItem.value.switchLoading = false;
    await changeSysUserStatus({
      userId: activeItem.value.id,
      userStatus: !activeItem.value.accountStatus,
    });
    seachTableRef.value.handlerSearch();
  } catch (error) {
    activeItem.value.switchLoading = false;
  }
};
const activeItem = ref();
const activeItemFun = (row) => {
  activeItem.value = row;
};
const delItem = ref();
const delMessageBoxRef = ref();
const delMessageConfirm = async () => {
  await deleteSysUser(delItem.value?.id);
  seachTableRef.value.handlerSearch();
};

const setForm = async () => {
  // 部门
  formInline.value[1].loading = true;
  const depRes = await queryDepartmentListPage();
  formInline.value[1].data = depRes.records.map((v) => ({
    label: v.departmentName,
    value: v.id,
  }));
  formInline.value[1].loading = false;
  // 角色
  formInline.value[2].loading = true;
  const roleRes = await queryRoleList()
  formInline.value[2].data = roleRes.records.map((v) => ({
    label: v.roleName,
    value: v.id,
  }));
  formInline.value[2].loading = false;
};




onActivated(async () => {
  await setForm();
  let closeTagName = sessionStorage.getItem("closeTagName");
  if (closeTagName == "StaffManageEdit") {
    //编辑退回时
    seachTableRef.value.handlerSearch(); //刷新当前页
  } else if (closeTagName == "StaffManageAdd") {
    //新增退回时
    seachTableRef.value.initSearch(); //返回第一页并刷新
  }
  instance.proxy.$forceUpdate(); //重新渲染demo
  sessionStorage.removeItem("closeTagName"); //溢出缓存中的tag名
});
</script>

<template>
  <div class="page-content">
    <SeachTable
      :tableType="1"
      ref="seachTableRef"
      :forms="formInline"
      :btnLefts="btnLefts"
      :tableLoading="tableLoading"
      :tableConfig="tableConfig"
      :tableData="tableData"
      :totalPage="totalPage"
      @handlerSearch="handlerSearch"
    >
      <template #userRoleList="{ row }">
        <div v-if="row.userRoleList?.length">
          <TabRole
            :id="item"
            :key="item"
            :origin="row.userRoleList"
            :list="formInline[2].data"
            :index="index"
            v-for="(item,index) in row.userRoleList"
          ></TabRole>
        </div>
        <div v-else>-</div>
      </template>
      <template #userDepartmentList="{ row }">
        <div v-if="row.userDepartmentList?.length">
          <TabDepartment
            :id="item"
            :key="item"
            :index="index"
            :origin="row.userDepartmentList"
            :list="formInline[1].data"
            v-for="(item,index) in row.userDepartmentList"
          ></TabDepartment>
        </div>
        <div v-else>-</div>
      </template>
      <template #accountStatus="{ row }">
        <el-switch
          v-model="row.accountStatus"
          :disabled="row.accountType == 1"
          :loading="row.switchLoading"
          :before-change="switchChange"
          @click="activeItemFun(row)"
        />
      </template>
    </SeachTable>
  </div>
  <MessageBox
    ref="messageBoxRef"
    :content="'禁用后，该员工将无法登录系统，确定禁用？'"
    @confirm="messageConfirm"
  />
  <MessageBox
    ref="delMessageBoxRef"
    :content="'删除后，员工的账号信息将同步被删除，确认删除吗？'"
    :rightBtnTxt="'删除'"
    @confirm="delMessageConfirm"
  />
</template>

<style lang="less" scoped></style>
